package com.summer.data.jql.table;

import com.summer.data.Jsql;
import com.summer.data.dialect.Dialect;
import com.summer.data.jql.Context;
import com.summer.data.jql.concept.Field;
import com.summer.data.jql.exception.NotAliasException;

/**
 * @author 345480567@qq.com
 */
public class NamedJqlColumn<T> implements Field<T> {

    private final String columnName;
    private final JqlTable host;

    public NamedJqlColumn(JqlTable host, String fieldName) {
        this.host = host;
        this.columnName = fieldName;
    }

    public NamedJqlColumn(JqlTable host, String fieldName, Class<T> clazz) {
        this.host = host;
        this.columnName = fieldName;
    }

    @Override
    public Jsql toFieldSql(Context ctx, Dialect dialect) {
        String format = "%s.%s";
        String alias = ctx.getAlias(host);
        if (alias == null) {
            throw new NotAliasException("Jql 用作子查询时必须被 alias");
        }
        return Jsql.format(format, alias, columnName);
    }
}
